package com.example.alldemo.rabitmq;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;

import javax.annotation.Resource;

public class WorkModel {

    @Autowired
    private ConnectionFactory connectionFactory;

    @Autowired
    private RabitMqconfig rabitMqconfig;
    //自定义监听器容器
    @Bean
    public SimpleMessageListenerContainer messageContainer1() {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
        container.setQueues(rabitMqconfig.directQueue());
        container.setExposeListenerChannel(true);
        //设置最大并发消费者数量
        container.setMaxConcurrentConsumers(10);
        //设置当前并发消费者数量
        container.setConcurrentConsumers(2);
        //修改为手动确认模式
        container.setAcknowledgeMode(AcknowledgeMode.MANUAL);//消息确认后才能删除
        //一个消费者每次处理一条消息
        container.setPrefetchCount(1);//每次处理1条消息
        container.setMessageListener(new ChannelAwareMessageListener() {
            public void onMessage(Message message, Channel channel) throws Exception {
                byte[] body = message.getBody();
                Thread.sleep(2000);
                System.out.println("消费者接收到消息 : " + new String(body));
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            }
        });
        return container;
    }

}
